package cn.zyjblogs.starter.redis.utils.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Copyright (C), 2021, 北京同创永益科技发展有限公司
 *
 * @author zhuyijun
 * @version 3.0.0
 * @description
 * @date 2022/5/23 11:02
 */
@Slf4j
@Component
public class RedisLockTemplate {

    @Resource
    private LockExecutor<String> RedisTemplateLockExecutor;
    /**
     * 默认失效时间
     */
    private Long defaultExpire = 30000L;
    private Long defaultAcquireTimeout = 3000L;
    /**
     * 获取锁失败时重试时间间隔 单位：毫秒
     */
    private Long retryInterval = 100L;

    @Value("${zyjblogs.redis.prefix:lock}")
    private String prefix;
    /**
     * 获取锁（不推荐）
     *
     * @param key
     * @param expire
     * @return
     */
    public RedisLock lock(String key, long expire) {
        return lock(key, expire, 0, null);
    }
    /**
     * 加锁方法
     *
     * @param key            锁key 同一个key只能被一个客户端持有
     * @param expire         过期时间(ms) 防止死锁
     * @param acquireTimeout 尝试获取锁超时时间(ms)
     * @return 加锁成功返回锁信息 失败返回null
     */
    public RedisLock tryLock(String key, long expire, long acquireTimeout) {
        return lock(key, expire, acquireTimeout, null);
    }

    /**
     * 加锁方法
     *
     * @param key            锁key 同一个key只能被一个客户端持有
     * @param expire         过期时间(ms) 防止死锁
     * @param acquireTimeout 尝试获取锁超时时间(ms)
     * @param executor       执行器
     * @return 加锁成功返回锁信息 失败返回null
     */
    public RedisLock lock(String key, long expire, long acquireTimeout, LockExecutor executor) {
        key = prefix + key;
        LockExecutor lockExecutor = obtainExecutor(executor);
        expire = expire < 0 ? defaultExpire : expire;
        long currentAcquireTimeout = acquireTimeout < 0 ? defaultAcquireTimeout : acquireTimeout;
        int acquireCount = 0;
        String value = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        try {
            do {
                acquireCount++;
                Object lockInstance = lockExecutor.acquire(key, value, expire, acquireTimeout);
                if (null != lockInstance) {
                    log.debug("加锁成功 key:{}",key);
                    return RedisLock.builder()
                            .lockKey(key)
                            .lockValue(value)
                            .expire(expire)
                            .acquireTimeout(currentAcquireTimeout)
                            .acquireCount(acquireCount)
                            .lockInstance(lockInstance)
                            .lockExecutor(lockExecutor)
                            .build();
                }
                TimeUnit.MILLISECONDS.sleep(retryInterval);
            } while (System.currentTimeMillis() - start < currentAcquireTimeout);
        } catch (InterruptedException e) {
            log.error("lock error", e);
            throw new RuntimeException("加锁失败");
        }
        return null;
    }

    protected LockExecutor obtainExecutor(LockExecutor lockExecutor) {
        if (null == lockExecutor) {
            return RedisTemplateLockExecutor;
        }
        return lockExecutor;
    }

    /*** 
     * 解锁
     * @param redisLock
     * @author zhuyijun
     * @Description
     * @date 11:29
     */
    public boolean unLock(RedisLock redisLock) {
        if (null == redisLock) {
            return false;
        }
        return redisLock.getLockExecutor().releaseLock(redisLock.getLockKey(), redisLock.getLockValue(),
                redisLock.getLockInstance());
    }
}
